#include <iostream>
#include <vector>
#include <arpa/inet.h>
#include "deserializer.h"

#define SIZE 4096

using namespace std;

vector<A*> A :: a_objects = vector<A*>();
vector<B*> B :: b_objects = vector<B*>();

vector<Consumer*> consumers = vector<Consumer*>();
vector<Serializable*> objects = vector<Serializable*>();

int talk_with_client(int socket) {
	char buffer[SIZE];
	int size = 0;
	while(true) {
		size = recv(socket, buffer, SIZE,0);
		if(size <= 0) {
			if(size < 0)
				perror("Receive: ");
			//close_connection(socket);
				return -1;
		}
		const string text(buffer);
		for(int i = 0; i < objects.size(); i++) {
			objects[i]->deserialize(text);
		}
		for(int i = 0; i < consumers.size(); i++) {
			consumers[i]->consume();
		}	
	}
	return 0;
}

int main(int argc, char ** argv) {
	A* a = new A();
	B* b = new B();
	ConsumerA* a_c = new ConsumerA();
	ConsumerB* b_c = new ConsumerB();
	
	consumers.push_back(a_c);
	consumers.push_back(b_c);
	
	objects.push_back(a);
	objects.push_back(b);
	
    int listen_sckt = socket (AF_INET, SOCK_STREAM, 0);
	if(listen_sckt == -1) {	
		perror("Opening socket: ");
		close(listen_sckt);
		return -1;
	}
	
	sockaddr_in *client = new sockaddr_in;
	int errcheck = 0;
	sockaddr_in *server = new sockaddr_in;
	server->sin_family = AF_INET;
	server->sin_addr.s_addr = INADDR_ANY;
	server->sin_port = htons ((errcheck = atoi(argv[1])));
	if(errcheck ==0) {
		close(listen_sckt);
		return 0;
	}
	errcheck = bind(listen_sckt,(sockaddr*)server,sizeof(sockaddr_in));
	
	errcheck = listen(listen_sckt,1);
	if(errcheck == -1)
	{
		perror("Listen: ");
		close(listen_sckt);
		delete server;
		delete client;
		return errcheck;
	}
	while(true) {
		unsigned int size =  sizeof(sockaddr_in);
		int client_sckt = accept(listen_sckt,(sockaddr*)client, &size);
		talk_with_client(client_sckt);
	}	
	close(listen_sckt);
	delete server;
	delete client;
	delete a;
	delete b;
	delete a_c;
	delete b_c;
	return 0;
}




